﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FALibrary.Sequence
{
    public abstract class FASequenceItem : FAObject
    {
        protected long PoleTime { get; private set; }
        protected long NowTime { get; private set; }
        protected Action<FASequence, long> Executor { get; set; }
        
        public void Execute(FASequence actor)
        {
            if (PoleTime == 0)
            {
                NowTime = DateTime.Now.Ticks;
                PoleTime = NowTime;
                FirstExecute(actor);
            }
            else
                NowTime = DateTime.Now.Ticks;

            Executor(actor, (NowTime-PoleTime)/10000);
        }

        public void ClearState()
        {
            NowTime = 0;
            PoleTime = 0;
        }

        protected abstract void FirstExecute(FASequence actor);        
    }

    public class FAAutoNextSequenceItem : FASequenceItem 
    {
        private Action<object> _autoNextExecutor = null;

        public FAAutoNextSequenceItem(Action<object> actoin)
        {
            _autoNextExecutor = actoin;
            Executor = AutoNextExecute;
        }

        private void AutoNextExecute(FASequence actor, long time)
        {            
            _autoNextExecutor(actor);
        }

        protected override void FirstExecute(FASequence actor)
        {
        }
    }

    public class FAConditionalSequenceItem : FASequenceItem 
    {
        private Action<FASequence, long> _action = null;

        public FAConditionalSequenceItem(Action<FASequence, long> actoin)
        {
            _action = actoin;
            Executor = ExecuteAction;
        }

        private void ExecuteAction(FASequence actor, long time)
        {
            _action(actor, time);
        }

        protected override void FirstExecute(FASequence actor)
        {
        }
    }

    public class FASequenceCombinationSequenceItem : FASequenceItem 
    {
        private List<FASequence> _sequenceList = new List<FASequence>();

        public FASequenceCombinationSequenceItem(params FASequence[] sequences)
        {
            _sequenceList.AddRange(sequences);
        }

        protected override void FirstExecute(FASequence actor)
        {
            foreach (FASequence item in _sequenceList)
            {
                item.Start(actor);
            }
        }

        private void ConfirmTerminatedSequences(FASequence actor, long time)
        {
            foreach (FASequence item in _sequenceList)
            {
                if (item.State != SequenceState.Terminated)
                    return;
            }

            actor.NextStep();
        }
    }
}
